package cn.sunxiansheng.validation.controller;

import cn.sunxiansheng.tool.response.ResultWrapper;
import cn.sunxiansheng.validation.entity.JsrReq;
import cn.sunxiansheng.web.base.BaseController;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * Description: JSR-303校验控制器
 *
 * @Author sun
 * @Create 2024/10/28 11:19
 * @Version 1.0
 */
@RestController
public class JsrController extends BaseController {

    @RequestMapping("/jsr")
    public ResultWrapper<Map<String, String>> validate(@RequestBody @Valid JsrReq req, BindingResult result) {
        if(result.hasErrors()){
            Map<String,String> map = new HashMap<>();
            //1、获取校验的错误结果
            result.getFieldErrors().forEach((item)->{
                //FieldError 获取到错误提示
                String message = item.getDefaultMessage();
                //获取错误的属性的名字
                String field = item.getField();
                map.put(field,message);
            });
            return ResultWrapper.fail(401, "参数校验失败", map);
        }
        return ResultWrapper.ok(null);
    }
}















